#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

class MessagePublisher {
private:
    int socket_fd;
    struct sockaddr_in server_addr;
    const int PORT = 8888;

public:
    MessagePublisher() {
        // 创建UDP套接字
        socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (socket_fd < 0) {
            std::cerr << "Socket creation failed." << std::endl;
            exit(EXIT_FAILURE);
        }

        // 配置服务器地址
        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(PORT);
        server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    }

    ~MessagePublisher() {
        close(socket_fd);
    }

    void publish(float value, const std::string& message) {
        // 创建消息格式: float|string
        std::stringstream ss;
        ss << value << "|" << message;
        std::string data = ss.str();
        
        // 发送消息
        sendto(socket_fd, data.c_str(), data.length(), 0, 
               (struct sockaddr*)&server_addr, sizeof(server_addr));
        
        std::cout << "Published: " << data << std::endl;
    }
};

int main() {
    MessagePublisher publisher;
    float value;
    std::string message;
    
    while (true) {
        std::cout << "Enter float value (or -1 to quit): ";
        std::cin >> value;
        
        if (value == -1) break;
        
        std::cout << "Enter string message: ";
        std::cin.ignore(); // 清除输入缓冲
        std::getline(std::cin, message);
        
        publisher.publish(value, message);
    }
    
    return 0;
}
